<?php
class ProductType extends AppModel {
	var $name = 'ProductType';
	var $primaryKey  = 'id';
	var $useTable = "product_types";
	var $recursive = 1;
	
	var $hasMany = array(
		'Product' => array(
			 'className'     => 'Product',            
			 'foreignKey'    => 'type'
	));

	function get($id) {
		return $this->find('first', array(
			'conditions' => array(
				'id' => $id
		)));
	}

	/**
	 * tạo cây nhóm sản phẩm ...
	 * @return array
	 */
	 /*--------------------Start get tree--------------------*/
	function getList() {
		$cache = Cache::read("product_type_list");

		if ( $cache === false) {
			$list = null;
			$items = $this->find('all');
			$this->genTreeList($items, $list);
			$cache = $list;
			Cache::write("product_type_list", $cache);
		}

		return $cache;
	}

	private function genTreeList($items, &$list, $spec='', $parent=0) {
		$_child = false;
		if($parent == 0) {
			$spec = '';
		} else {
			$spec .= '----';
		}
		foreach($items as $r) {
			if($r[$this->alias]['parent'] == $parent) {
				$_child = true;
				$list[$r[$this->alias]['id']] = $spec . $r[$this->alias]['name'];
				$_child = $this->genTreeList($items, $list, $spec, $r[$this->alias]['id']);
			}
		}
		return $_child;
	}
	 /*--------------------End get tree--------------------*/

	 function getTree($parent = null) {
		$a = array();
		if ($parent > 0) {
			$a = $this->find('list',array(
				'conditions' => array(
					'parent' => $parent
				),
				'fields' => array('id')
			));
		}
		$a[$parent] = $parent;
		return $a;
	 }

	 function genTree($list, $parent = 0, $level = 0,$lang) {
			$_haveChild = false;
			foreach($list as $item) {
				if($item['ProductType']['parent'] == $parent) {
					$_haveChild = true;
					break;
				}
			}
			if($_haveChild) {
				echo "<ul>";
				foreach($list as $item) {
					if($item['ProductType']['parent'] == $parent) {
						echo "<li>";
						if ($level == 0 || $level == 1) {
							echo '<a href="'.Router::url(array(
								'plugin'	=> NULL,
								'controller' => 'product',
								'action' => 'index',$item['ProductType']['id'],Inflector::stripUnicode($item['ProductType']['name_'.$lang])
								), array('class' => 'sub')).'">'.$item['ProductType']['name_'.$lang].'</a>';
						}
						else {
							echo '<a href="'.Router::url(array(
								'plugin'	=> NULL,
								'controller' => 'product',
								'action' => 'view',$item['ProductType']['id'],Inflector::stripUnicode($item['ProductType']['name_'.$lang])
								), array('class' => 'sub')).'">'.$item['ProductType']['name_'.$lang].'</a>';
						}

						$_haveChild = $this->genTree($list, $item['ProductType']['id'],$level + 1,$lang);
						echo "</li>";
						if(!$_haveChild) continue;
					}
				}
				echo '</ul>';
			}
			return $_haveChild;
		}
	}
?>